package com.zx.gateway.handle;

import com.zx.core.utils.ServletUtils;
import com.zx.core.wrapper.ResponseWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * <p>
 * description: 全局异常处理 <br>
 * create: 2024-08-15 13:33
 * </p>
 *
 * @author zhou  xun
 */
@Component
@Order(-1) // 设置优先级，确保先执行自定义的异常处理器
@Slf4j
public class CustomWebExceptionHandler implements ErrorWebExceptionHandler {
    @Override
    public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
        ServerHttpResponse response = exchange.getResponse();
        //检查响应是否已经被发送到客户端。
        // 在 HTTP 协议中，一旦响应被提交（即头部被发送），就无法再修改响应的状态码或头部信息了。
        // 因此，如果响应已经提交，那么再尝试修改它就没有意义了。
        if (exchange.getResponse().isCommitted()) {
            return Mono.error(ex);
        }
        String msg;
        if (ex instanceof ResponseStatusException responseStatusException) {
            response.setStatusCode(responseStatusException.getStatusCode());
            msg = responseStatusException.getMessage();
        } else {
            response.setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR);
            msg = "内部服务器错误";
        }
        log.error("[网关异常处理]请求路径:{},异常信息:{}", exchange.getRequest().getPath(), ex.getMessage());
        ResponseWrapper result = new ResponseWrapper();
        result.fail(msg);
        DataBuffer buffer = ServletUtils.getDataBuffer(result, response.bufferFactory());
        return response.writeWith(Mono.just(buffer));
    }
}
